<script setup lang="ts">
import { ref, reactive, defineProps, watch } from 'vue'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const emits = defineEmits(['close'])
const closeDialog = () => {
    emits('close', false)
}
const props = defineProps({
    isShow: {
        type: Boolean,
        default: false
    }
})
const formInline = reactive({
    phone: '',
    code: '',
})

const rules = {
    phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
    ],
    code: [
        { required: true, message: '请输入短信验证码', trigger: 'blur' },
    ],
}
const countdown = ref(60);
const isSending = ref(false);
const sendCode = () => {
        if (isSending.value) return;
        isSending.value = true;
        const timer = setInterval(() => {
            if (countdown.value === 0) {
                clearInterval(timer);
                isSending.value = false;
                countdown.value  = 60;
            } else {
                countdown.value--;
            }
        }, 1000);
    ElMessage.success('验证码已发送');
}
const onSubmit = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            ElMessage.success('成功')
            dialogVisible.value = false
        } else {
            // ElMessage.error('请修正表单中的错误')
        }
    })
}

watch(() => props.isShow, (val) => {
    dialogVisible.value = val
}, { immediate: true })
</script>

<template>
    <el-dialog
    v-model="dialogVisible"
    title="修改绑定手机"
    width="520"
    @close="closeDialog"
    >
        <div class="dialog-form">
            <el-form :model="formInline" :rules="rules" ref="formRef" label-width="130px">
                <el-form-item label="新的手机号码：" prop="phone">
                    <el-input v-model="formInline.phone" placeholder="请输入手机号" style="width: 225px"/>
                </el-form-item>
                <el-form-item label="短信验证码：" prop="code">
                    <el-input v-model="formInline.code" placeholder="请输入验证码" style="width: 165px"/>
                    <el-button @click="sendCode" class="send-code-btn">
                        {{ isSending ? `重新发送(${countdown}s)` : '发送验证码' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
        <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmit($refs.formRef)">
                确定
            </el-button>
        </div>
    </template>
    </el-dialog>
</template>

<style scoped lang='scss'>
    .forget-password{
        line-height: 1.4;
        margin-left: 20px;
    }
    .send-code-btn{
        margin-left: 10px;
    }
</style>